package com.shawn.baseappbygroovydsl.ui.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View

/**
 * 描述：
 * 作者： shawn
 * 时间： 2024/8/2017:27
 */
class HighlightView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    private val paint = Paint().apply {
        color = Color.parseColor("#B3000000")
        isAntiAlias = true
    }

    private var highlightRect: RectF? = null
    private var animRect: RectF? = null

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 创建新的图层
        val saved = canvas.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null)

        // 绘制黑色背景
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)

        // 使用 DST_OUT 模式来清除高亮区域
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)

        // 绘制动画效果
        animRect?.let {
            canvas.drawRoundRect(it, 15f, 15f, paint)
        }

        // 还原 xfermode 和图层
        paint.xfermode = null
        canvas.restoreToCount(saved)
    }

    fun startHighlight(view: View) {
        val location = IntArray(2)

        view.getLocationOnScreen(location)

        val relativeX = view.left.toFloat()
        val relativeY = view.top.toFloat()

        // 获取目标 View 的位置和大小
//        val location = IntArray(2)
//        view.getLocationInWindow(location)
        highlightRect = RectF(relativeX, relativeY,
            (relativeX + view.width),
            (relativeY + view.height))

        // 初始化动画矩形
        animRect = RectF(0f, 0f, 0f, 0f)
        invalidate()

        // 动画从四个方向扩展
        val animator = ValueAnimator.ofFloat(0f, 1f).apply {
            duration = 1000L
            addUpdateListener { animation ->
                val progress = animation.animatedValue as Float
                animRect?.left = highlightRect!!.left * progress
                animRect?.top = highlightRect!!.top * progress
                animRect?.right = width - (width - highlightRect!!.right) * progress
                animRect?.bottom = height - (height - highlightRect!!.bottom) * progress
                invalidate()
            }
        }
        animator.start()
    }
}
